<template>
  <div class="el-form">
    <slot></slot>
  </div>
</template>

<script setup lang="ts">
import { type PropType, provide } from "vue";
import { type Rules } from "async-validator";
import { ref } from "vue";
import { emitter } from "../../emitter";
import { type FormItem, key } from "./type";

const props = defineProps({
  model: { type: Object, required: true },
  rules: { type: Object as PropType<Rules> },
});

provide(key, {
  model: props.model,
  rules: props.rules,
});

const items = ref<FormItem[]>([]);

emitter.on("addFormItem", (item) => {
  items.value.push(item);
});

// eslint-disable-next-line no-unused-vars
function validate(cb: (isValid: boolean) => void) {
  const tasks = items.value.map((item) => item.validate());
  Promise.all(tasks)
    .then(() => {
      cb(true);
    })
    .catch(() => {
      cb(false);
    });
}

defineExpose({
  validate,
});

defineOptions({ name: "ElForm" });
</script>

<style lang="scss">
@import "../styles/mixin";
@include b(form) {
  margin-top: 20px;
  box-sizing: border-box;
  flex-shrink: 0;
  width: 300px;
}
</style>
